package com.itboye.jmsfhz.main;

import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.itboye.app.mian.activity.AboutActivity;
import com.itboye.baidu.util.LocationService;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DebugLog;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.inageview.RoundImageView;
import com.itboye.jmsfhz.R;
import com.itboye.jmsfhz.app.MainApplication;
import com.itboye.jmsfhz.app.logincontroller.LoginController;
import com.itboye.jmsfhz.data.model.MeTouGuoDeBean;
import com.itboye.jmsfhz.data.presenter.Projectpresenter;
import com.itboye.jmsfhz.widget.CustomDialog;
import com.itboye.jmsfhz.widget.UIAlertView;

/**
 * 个人中心
 * 
 * @author Mr
 * 
 */
public class WoMengFragment extends BaseFragment implements OnClickListener,
		Observer {
	/** 设置 **/
	private RelativeLayout relayoutSetting;
	private LocationService locationService;
	RelativeLayout adddress_manage;
	private RoundImageView roundImage;
	RelativeLayout relayoutZiLiao, relayoutMeispaing, relayoutZhangHuAnQuan;
	MeTouGuoDeBean bean;
	Projectpresenter projectpr;
	TextView txtUserName,textView1;
	public static ScrollView scroll;
	String page_size = 10 + "";
	String page_num = 1 + "";
	String time;
	UIAlertView uiAlertView;
	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_womeng;
	}

	public static String AVARTACTION = "com.itboye.avart";

	public static String EMAILACTION = "com.itboye.email";
	String uid;

	@Override
	public void onMyActivityCreated() {
		projectpr = new Projectpresenter(this);
		bean = new MeTouGuoDeBean();
		bean.setPage_num(page_num);
		bean.setPage_size(page_size);
		time = String.valueOf((int) (Math.random() * 10));

		uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID, "");
		System.out.println(">>>>>>>>>>>>>>>>>>>>uid" + uid);
		XImageLoader.load((String) SPUtils.get(getActivity(), null,
				SpPublicParams.URL, ""), roundImage);
//		onMeShouDao();
		studengt();
		Qiye();
		scroll.smoothScrollTo(0, 0);
		// 注册广播

		IntentFilter intentFilterAvart2 = new IntentFilter("changeavart");
		getActivity().registerReceiver(avartBroadcastReceiver,
				intentFilterAvart2);
		// 注册广播
		IntentFilter intentFilterAvart = new IntentFilter(AVARTACTION);
		getActivity().registerReceiver(avartBroadcastReceiver,
				intentFilterAvart);

		// 更新呢称
		IntentFilter intentFilterAvart43 = new IntentFilter("titlenikname");
		getActivity().registerReceiver(avartBroadcastnikname,
				intentFilterAvart43);

		IntentFilter intentFilterAvartstudent = new IntentFilter("studengt");
		getActivity().registerReceiver(studengt, intentFilterAvartstudent);

		IntentFilter UnserQiye = new IntentFilter("qiye");
		getActivity().registerReceiver(qiye, UnserQiye);

	}

	BroadcastReceiver avartBroadcastnikname = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String resultData = (String) SPUtils.get(getActivity(), null,
					SpPublicParams.NICK_NAME, "");
			txtUserName.setText(resultData);
		};
	};

	BroadcastReceiver avartBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			XImageLoader.load((String) SPUtils.get(getActivity(), null,
					SpPublicParams.URL, ""), roundImage);

		};
	};

	BroadcastReceiver studengt = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			studengt();

		};
	};

	BroadcastReceiver qiye = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			Qiye();

		};
	};

	public void studengt() {
			relayoutZhangHuAnQuan.setVisibility(View.VISIBLE);
			relayoutMeispaing.setVisibility(View.GONE);
	}

	public void Qiye() {
			relayoutZhangHuAnQuan.setVisibility(View.GONE);
			relayoutMeispaing.setVisibility(View.VISIBLE);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (SPUtils.get(getActivity(), null, SpPublicParams.URL, "") == null) {

		} else {
			XImageLoader.load((String) SPUtils.get(getActivity(), null,
					SpPublicParams.URL, ""), roundImage);
		}
		if (SPUtils.get(getActivity(), null, SpPublicParams.USER_NAME, "") != null) {
			txtUserName.setText((String) SPUtils.get(getActivity(), null,
					SpPublicParams.NICK_NAME, ""));

		}

	}

	public static void setPosition() {
		scroll.smoothScrollTo(0, 0);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.relayoutZiLiao:
			// Intent intent1 = new Intent(getActivity(),
			// ActivityGeRenData.class);
			// startActivityForResult(intent1, 101);
			LoginController.queryMyMessae(getActivity(), null);
			break;
		case R.id.relayoutSetting:
			Intent intent = new Intent(getActivity(), AboutActivity.class);
			startActivity(intent);
			break;
		case R.id.roundImage:
			LoginController.queryMyMessae(getActivity(), null);
			break;
		case R.id.relayoutZhangHuAnQuan:
//			Intent intent2 = new Intent(getActivity(), MeShouDaoActivity.class);
//			startActivity(intent2);
			LoginController.getShoudao(getActivity(), null);
			break;
		case R.id.relayoutMeispaing:
			showDelDialog();
			// projectpr.getShouDao(uid, page_num, page_size);
			break;
		default:
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub

		ResultEntity model = super.handlerError(data);

		if (model.getEventType() == projectpr.TouSuccessEvent) {
		}
	}
	
	
	
	private void showDelDialog() {
		uiAlertView = new UIAlertView(getActivity(), "温馨提示！", "请登录电脑端网站查看", "否", "是");
		uiAlertView.show();

		uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {

			public void doLeft() {
				uiAlertView.dismiss();
			}

			public void doRight() {
				uiAlertView.dismiss();
			
			}
		});
	}
	
	
	/**
	 * 显示请求字符串
	 * 
	 * @param str
	 */
	public void logMsg(String str) {
		try {
			if (textView1 != null)
				textView1.setText(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		DebugLog.v(str, str);
		System.out.print("定位系统："+str);
	}

	
	/***
	 * Stop location service
	 */
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		locationService.unregisterListener(mListener); //注销掉监听
		locationService.stop(); //停止定位服务
		super.onStop();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// -----------location config ------------
//		locationService = ((LocationApplication) getApplication()).locationService; 
		locationService=MainApplication.locationService;
		//获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
		locationService.registerListener(mListener);
		//注册监听
		int type =getActivity(). getIntent().getIntExtra("from", 0);
		if (type == 0) {
			locationService.setLocationOption(locationService.getDefaultLocationClientOption());
		} else if (type == 1) {
			locationService.setLocationOption(locationService.getOption());
		}
		

			locationService.start();// 定位SDK
									// start之后会默认发起一次定位请求，开发者无须判断isstart并主动调用request
			locationService.stop();
//
	}

	
	/*****
	 * @see copy funtion to you project
	 * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
	 *
	 */
	private BDLocationListener mListener = new BDLocationListener() {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// TODO Auto-generated method stub
			if (null != location && location.getLocType() != BDLocation.TypeServerError) {
				StringBuffer sb = new StringBuffer(256);
//				sb.append("time : ");
				/**
				 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
				 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变*/
				sb.append(location.getAddrStr());
				sb.append(location.getLocationDescribe());
				if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
					sb.append("\nspeed : ");
					sb.append(location.getSpeed());// 速度 单位：km/h
					sb.append("\nsatellite : ");
					sb.append(location.getSatelliteNumber());// 卫星数目
					sb.append("\nheight : ");
					sb.append(location.getAltitude());// 海拔高度 单位：米
					sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
					sb.append("\ndescribe : ");
					sb.append("gps定位成功");
				} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
					// 运营商信息
				    if (location.hasAltitude()) {// *****如果有海拔高度*****
				        sb.append("\nheight : ");
	                    sb.append(location.getAltitude());// 单位：米
				    }
				} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
					sb.append("\ndescribe : ");
					sb.append("离线定位成功，离线定位结果也是有效的");
				} else if (location.getLocType() == BDLocation.TypeServerError) {
					sb.append("\ndescribe : ");
					sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
				} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
					sb.append("\ndescribe : ");
					sb.append("网络不同导致定位失败，请检查网络是否通畅");
				} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
					sb.append("\ndescribe : ");
					sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
				}
				logMsg(sb.toString());
			}
		}

	};
}
